<template>
  <div class="app-container">
    <el-card class="box-card search-div" v-if="showSearch">
      <el-form :inline="true" :model="listQuery" ref="userQueryForm">
        <el-form-item label="关键词">
          <el-input placeholder="请输入姓名或手机号码" v-model="listQuery.searchWord" clearable/>
        </el-form-item>
        <el-form-item label="部门" style="width:20%;white-space: nowrap;"><!--append-to-body此属性用来解决下拉被遮挡的问题-->
          <treeselect :append-to-body='true' v-model="listQuery.deptIds" :multiple="false" :options="deptData" :load-options="loadOptions" :default-expand-level="2" placeholder="请选择部门"/>
        </el-form-item>
        <el-form-item label=""></el-form-item>
        <el-form-item label=""></el-form-item>
        <el-form-item label=""></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="listQuery.status" style="width:80px" clearable>
            <el-option label="所有" value=""></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="冻结" value="1"></el-option>
          </el-select>
        </el-form-item>
       <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
       <el-button @click="handleResetQuery" icon="el-icon-refresh">重置</el-button>
      </el-form>
    </el-card>
    <el-card class="box-card" style="z-index: 10;">
      <div slot="header" class="clearfix">
        <el-button type="primary" v-hasPermi="['sys_user_add']" class="el-icon-plus" @click="add">新增</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
      <el-table :data="list" v-loading.body="listLoading" border fit highlight-current-row class="table-list">
        <el-table-column label="序号" type="index" min-width="5%"/>
        <el-table-column align="center" label="姓名" prop="userName" width="220">
        </el-table-column>
        <el-table-column align="center" label="性别" prop="sex" width="60">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex==1">男</el-tag>
            <el-tag v-if="scope.row.sex==0" type="danger">女</el-tag>
            <el-tag v-if="scope.row.sex==2" type="danger">保密</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="手机号码" prop="phoneNumber" width="220">
        </el-table-column>
        <el-table-column align="center" label="部门/岗位" prop="deptPostName">
          <template slot-scope="scope">
            <div style="white-space: pre-line">{{scope.row.deptPostName}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色" prop="roleIds">
          <template slot-scope="scope">
            <div style="white-space: pre-line">{{showRoleName(scope.row.roleIds)}}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="个性签名" prop="remark">
        </el-table-column>
        <el-table-column label="状态" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0">正常</el-tag>
            <el-tag v-if="scope.row.status==1" type="danger">冻结</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作"  width="240">
          <template slot-scope="scope">
            <el-button plain v-hasPermi="['sys_user_edit']" type="violet" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button plain v-hasPermi="['sys_user_remove']" v-if="scope.row.status==0" type="danger" @click="handleStatus(scope.row.id,scope.row.status)">冻结</el-button>
            <el-button plain v-hasPermi="['sys_user_remove']" v-if="scope.row.status==1" type="success" @click="handleStatus(scope.row.id,scope.row.status)">启用</el-button>
            <el-button plain v-hasPermi="['sys_user_restpwd']" type="warning" @click="handleResetPasswrod(scope.row.id)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
   </el-card>
    <!--弹出框-->
    <el-dialog :title="dialogTitle" :width="'700px'" :visible.sync="showDialog" :close-on-click-modal="false">
      <el-form :rules="rules" ref="saveUserData" :model="saveUserData" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="saveUserData.userName" :maxlength="20"  clearable show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="saveUserData.phoneNumber" :maxlength="11" placeholder="请输入手机号码" clearable show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
           <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="saveUserData.sex" placeholder="请选择性别" style="width: 100%;" clearable>
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
           <el-form-item label="角色" prop="roleIds">
            <el-select v-model="saveUserData.roleIds" multiple placeholder="请选择角色" style="width: 100%;" clearable>
              <el-option v-for="item in roleData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="主岗位" prop="mainPostIdDeptId">
          <treeselect  v-model="saveUserData.mainPostIdDeptId" :disable-branch-nodes="true" :multiple="false" :options="deptAndPostData" :load-options="loadOptions" :default-expand-level="2" placeholder="请选择岗位"/>
        </el-form-item>
        <el-form-item label="副岗位" prop="postIdDeptIds">
          <treeselect  v-model="saveUserData.postIdDeptIds" :disable-branch-nodes="true" :multiple="true" :options="deptAndPostData" :load-options="loadOptions" :default-expand-level="2" placeholder="请选择岗位"/>
        </el-form-item>
         <el-form-item label="个性签名" prop="remark">
          <el-input v-model="saveUserData.remark" :rows="2" type="textarea" maxlength="100" placeholder="最多输入100个字符" clearable show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave('saveUserData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as user from './js/user'
import * as sysDept from '../dept/js/dept'
import * as sysRole from '../role/js/role'
import { mapGetters } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'userList',
  components: { Treeselect },
  data() {
     var checkPhone = (rule, value, callback) => {
        setTimeout(() => {
          if (!Number.isInteger(Number(value))) {
            callback(new Error('限定只能输入数字'));
          }else{
             callback();
          }
        }, 1000);
    };
    return {
      list: null,
      listLoading: true,
      total: 0,
      showSearch:true,
      listQuery: {
        page: 1, limit: 10, searchWord: '', deptId: null, status: '', deptIds: null
      },
      showDialog: false,
      saveUserData: {
        id: '', userName: '', sex: '1', phoneNumber: '', mainPostIdDeptId:null,postIdDeptIds: [],remark:''
      },
      postList: [],
      rules: {
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        mainPostIdDeptId: [{ required: true, message: '请选择岗位', trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入手机号码只能是数字', trigger: 'blur', validator: checkPhone }]
      },
      deptData: [],
      deptAndPostData: [],
      dialogTitle: '添加账号',
      roleData:[]
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getDeptAndPostTreeList()
    this.getRoleList()
  },
  methods: {
    loadOptions() {

    },
    getList() { // 获取所有用户
      this.listLoading = true
      this.listQuery.deptId = null
      const deptIds = this.listQuery.deptIds
      if (deptIds) {
        this.listQuery.deptId = deptIds.split('_')[0]
      }
      user.fetchList(this.listQuery).then(res => {
        this.list = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleResetQuery(){
      this.resetForm("userQueryForm")
      this.handleSearch()
    },
    // 部门岗位树
    getDeptAndPostTreeList() {
      sysDept.getDeptAndPostTreeList('').then((response) => {
        this.deptAndPostData = response.data
      })
    },
    // 部门树
    getDeptTree() {
      sysDept.getDeptTreeList().then((response) => {
        this.deptData = response.data
      })
    },
    //角色
    getRoleList(){
      sysRole.getList().then((response) => {
        this.roleData = response.data
      })
    },
    //显示角色名
    showRoleName(roleIds){
      var str = ''
      if(!roleIds)return str
      for(var i=0;i<roleIds.length;i++){
        var role = this.roleData.filter(function(fp) {
          return fp.value == roleIds[i]
        })
        var roleName = role[0]?role[0].label:''
        if(roleName!=''){
          str = roleName + '\n' + str
        }
      }
      return str;
    },
    handleResetPasswrod(id){
      this.$confirm('确定重置该用户密码', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        user.restPassword(id).then((response) => {
          this.$message({ type: 'success', message: '操作成功!' })
          this.getList()
        })
      }).catch(function(error) { console.log(error) })
    },
    // 禁用 启用
    handleStatus(userId, type) {
      var status = 1
      var msg = '请确定冻结该用户账号?'
      if (type === 1) {
        status = 0; msg = '请确定是否启用该用户账号?'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        user.updateUserStatusById(userId, status).then((response) => {
          this.$message({ type: 'success', message: '操作成功!' })
          this.getList()
        })
      }).catch(function(error) { console.log(error) })
    },
    // 新增
    add(pit, index) {
      this.showDialog = true
      this.dialogTitle = '添加账号'
      this.$nextTick(() => { // 清空表单数据
        this.resetForm('saveUserData')
        this.saveUserData.id = null
      })
    },
    // 编辑
    handleEdit(index, row) {
      this.showDialog = true
      this.dialogTitle = '编辑用户'
      this.$nextTick(() => {
        this.resetForm('saveUserData')
        this.saveUserData.id = row.id
        this.saveUserData.userName = row.userName
        this.saveUserData.sex = row.sex+''
        this.saveUserData.phoneNumber = row.phoneNumber
        this.saveUserData.postIdDeptIds = row.postIdDeptIds
        this.saveUserData.mainPostIdDeptId = row.mainPostIdDeptId
        row.roleIds.forEach(item => {
          this.saveUserData.roleIds.push(item+'');
        })
      })
    },
    // 保存
    onSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          user.save(this.saveUserData).then((response) => {
            this.showDialog = false
            this.$message({ type: 'success', message: '操作成功!' })
            this.getList()
          }).catch(function(error) {
            console.log(error)
          })
        }
      })
    }
  }
}
</script>
